/*
 * @Author: your name
 * @Date: 2020-11-06 14:58:38
 * @LastEditTime: 2021-06-02 11:22:35
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \ws-shop\src\store\mutations.js
 */
import Vue from 'vue'
import { Toast } from 'vant'
Vue.use(Toast)
export default {
  // 在项目中payload一般穿对象
  addToCart (state, { detail }) {
    // 添加购物车
    // 判断state里面有没有这个id对应的商品
    if (sessionStorage.getItem('user')) {
      const isExist = state.cart.some(shop => shop.id === detail.id)
      if (isExist) {
        state.cart = state.cart.map(shop => {
          if (shop.id === detail.id) {
            shop.count++
            shop.image = shop.image ? shop.image : shop.photo[0].url
          }
          return shop
        })
      } else {
        state.cart.push({
          ...detail,
          image: detail.image ? detail.image : detail.photo[0].url,
          count: 1,
          check: true
        })
      }
    } else {
      Toast('请先登录')
    }
  },
  collection (state, { detail }) {
    // 添加收藏
    // 判断state里面有没有这个id对应的商品
    if (sessionStorage.getItem('user')) {
      // console.log(state, detail)
      const isExist = state.collection.some(shop => shop.id === detail.id)
      if (isExist) {
        Toast('已收藏')
      } else {
        state.collection.push({
          ...detail,
          image: detail.image ? detail.image : detail.photo[0].url
        })
      }
    } else {
      Toast('请先登录')
    }
  },
  delCollectionShop (state, { id }) {
    state.collection = state.collection.filter(shop => shop.id !== id)
  },
  toggleCheck (state, { id }) {
    state.cart = state.cart.map(shop => {
      if (shop.id === id) shop.check = !shop.check
      return shop
    })
  },
  changeCountById (state, { id, num }) {
    state.cart = state.cart.map(shop => {
      if (shop.id === id) shop.count = num
      return shop
    })
  },
  delShop (state, { id }) {
    state.cart = state.cart.filter(shop => shop.id !== id)
  },
  toggleAllCheck (state, { isAllCheck }) {
    state.cart = state.cart.map(shop => {
      shop.check = !isAllCheck
      return shop
    })
  },
  changeIsBackShowAndTitle (state, { isBackShow, title }) {
    state.isBackShow = isBackShow
    state.title = title
  }
}
